#include "cangateway.h"
#include "can.h"
#include "tachometerui.h"

CanGateway::CanGateway()
{
}

CanGateway::CanGateway(QObject *parent) : SocketBase(parent)
{
    connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
}

CanGateway::~CanGateway()
{
}

void CanGateway::send(unsigned long int id, char * data, int num)
{
    can_t t;
    t.msgtype   = 'M';
    t.format    = 'S';
    t.id        = _htonl(id);
    t.num       = num;
    for(int i = 0; i < num; ++i)
        t.data[i] = data[i];
    this->send(t);
}

void CanGateway::send(can_t s)
{
    if (socket->state() == QAbstractSocket::ConnectedState)
    {
        QByteArray data;
        QDataStream out(&data, QIODevice::WriteOnly);
        out.setVersion(QDataStream::BigEndian);
        out.writeRawData((const char*) (&s), sizeof(can_t));
        socket->write(data);
        if(ProzessLeitSystem::instanze->canLogCheckBox())
        {
            logTextEdit->append(QString().sprintf("id%04d data01%x data02%x", s.id, s.data[0], s.data[1]));
            //logTextEdit->append(tr("LOG: new data received: id: %1, data0: %2, data1: %3").arg(s.id).arg(s.data[0]).arg(s.data[1]));
        }
    }
}

void CanGateway::readData()
{
    QDataStream in(socket);
    in.setVersion(QDataStream::BigEndian);

    if (socket->bytesAvailable() >= static_cast<qint64>(sizeof(can_t)))
    {
        can_t tmp;
        in.readRawData((char*) (&tmp), sizeof(can_t));
        tmp.id = SocketBase::_ntohl(tmp.id);
        recivedMsges.insert(tmp.id, tmp);
        if(ProzessLeitSystem::instanze->canLogCheckBox())
            logTextEdit->append(QString().sprintf("id%04d data01:%x data02:%x", tmp.id, tmp.data[0], tmp.data[1]));
            //logTextEdit->append(tr("LOG: new data received: id: %1, data0: %2, data1: %3").arg(tmp.id).arg(tmp.data[0]).arg(tmp.data[1]));
    }
}

const can_t & CanGateway::getMsg(id_t id) const
{
    return *recivedMsges.constFind(id);
}

bool CanGateway::hasMsg(id_t id) const
{
    return recivedMsges.contains(id);
}
